document.addEventListener('DOMContentLoaded', function () {
    const loginButton = document.getElementById('login-button'); // 使用 ID 选择登录按钮
    const modal = document.getElementById('myModal');
    const modalText = document.getElementById('modal-text');
    const span = document.getElementsByClassName('close')[0];
    // 获取注册按钮
    const registerButton = document.getElementById('register-button');

    // 确保按钮存在
    if (registerButton) {
        // 为注册按钮添加点击事件监听器
        registerButton.addEventListener('click', function () {
            console.log("注册按钮被点击");
            window.location.href = 'register.html'; // 设置跳转的目标页面地址
        });
    } else {
        console.log('注册按钮不存在');
    }

    const modalButton = document.getElementById('modal-button');
    loginButton.addEventListener('click', function () {
        console.log("登录按钮被点击");
        const username = document.querySelector('.input-box input[type="text"]').value;
        const password = document.querySelector('.input-box input[type="password"]').value;

        // 这里是调用后端登录接口的代码
        fetch('http://101.34.242.206:9990/users/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                password: password
            }),
        })
            .then(response => response.json())
            .then(data => {
                let message = '';
                if (data.code === 200) {
                    message = '登录成功';
                } else {
                    message = '登录失败';
                }
                modalText.innerText = message;
                modal.style.display = 'block';
            })
            .catch((error) => {
                console.error('登录请求失败:', error);
                modalText.innerText = '登录请求失败';
                modal.style.display = 'block';
            });
    });
    if (modalButton) {
        modalButton.addEventListener('click', function () {
            window.location.href = 'http://101.34.242.206:9990/blog.html'; // 设置跳转的目标页面地址
        });
    }else {
        console.log('按钮不存在');
    }
    span.onclick = function() {
        modal.style.display = 'none';
    }

    window.onclick = function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    }
});